package com.hankol.winecellar


import android.Manifest
import android.app.AlertDialog
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.text.InputFilter
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.ItemTouchHelper
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.*
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.hankol.winecellar.adapter.EditWineryUploadImageVideoAdapter
import com.hankol.winecellar.bean.LabelConfigFacilityBean
import com.hankol.winecellar.bean.WineryCoverBean
import com.hankol.winecellar.bean.WineryDataInfoBean
import com.hankol.winecellar.bean.WineryDetailPriewBean
import com.hankol.winecellar.databinding.ActivityEditOnlineWinecellarBinding
import com.hankol.winecellar.utils.EditInputUtils
import com.hankol.winecellar.utils.FlexBoxUtils
import com.hankol.winecellar.utils.RecyUtils
import com.media.utils.WineryAboutUtils
import com.hankol.winecellar.view.MyCircleProgress
import com.baselibrary.view.SpacesVerticalDec
import com.hankol.winecellar.view.WeChatPresenter
import com.hankol.winecellar.viewmodel.WineCellarViewModel
import com.media.publish.bean.MultiImageResp
import com.media.publish.utils.UploadMediaUtils
import com.ypx.imagepicker.ImagePicker
import com.ypx.imagepicker.bean.MimeType
import com.ypx.imagepicker.bean.selectconfig.CropConfig
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**线上酒窖编辑
 * @author: merbng
 * @description:
 */
@Route(path = ActivityRouter.WINE_CELLAR.EDIT_ONLINE_WINCELLAR)
class EditOnlineWinecellarActivity : BaseActivity(), View.OnClickListener, EditWineryUploadImageVideoAdapter.OnItemClickListener {

    private lateinit var viewModel: WineCellarViewModel
    private lateinit var binding: ActivityEditOnlineWinecellarBinding

    companion object {
        //线上数据
        const val FROM_TYPE_CURRENT = 0

        //预览数据
        const val FROM_TYPE_ADUIT = 1

    }

    //true：新增  false：回显
    var isNewAdd = true
    var dealerCode = ""

    //从哪进入的详情
    var fromType = FROM_TYPE_CURRENT
    override fun getLayoutId(): Int {
        return R.layout.activity_edit_online_winecellar
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(WineCellarViewModel::class.java)
        if (intent.extras.checkNotNull()) {
            if (ARouterUtils.parseParams(intent.extras!!, "isNewAdd").size > 0) {
                isNewAdd = ARouterUtils.parseParams(intent.extras!!, "isNewAdd")[0].toBoolean()
            }

            if (ARouterUtils.parseParams(intent.extras!!, "fromType").isNotEmpty()) {
                if (ARouterUtils.parseParams(intent.extras!!, "fromType")[0].checkNotNull()) {
                    fromType = ARouterUtils.parseParams(intent.extras!!, "fromType")[0].toInt()
                }
            }
        }
        initView()
        initListener()
        initObservere()
        loadData()

        //获取页面开始时间
        SensorsDataManager.instance.onCreateTime()
    }

    fun loadData() {
        getTempSave()
    }

    fun reqLeabl() {
        viewModel.reqgetWineryLabelConfig4Special()
        viewModel.reqgetWineryLabelConfig4Base()
    }

    var infoBean: WineryDataInfoBean? = null
    private fun initObservere() {
        viewModel.wineryDataInfoLD.observe(this, Observer {
            if (it.checkNotNull()) {
                infoBean = it
                //回显数据
                echoInfoData(it)
                reqLeabl()
            }
        })
        //特色标签
        viewModel.labelCongigLD4Special.observe(this, Observer {
            if (it.checkNotNull()) {
                totalTag4Fea.addAll(it)
                FlexBoxUtils.tagSelectList1.clear()
                binding.flboxSpecial.removeAllViews()
                if (isNewAdd) {//新增
                    if (SpUtils.getInstance().getAddEditOnlineWineyInfoJson().checkNotNull()) {
                        //草稿箱取出
                        val info = CommonUtil.jsonToBean(
                            SpUtils.getInstance().getAddEditOnlineWineyInfoJson(), WineryDataInfoBean::class.java
                        )
                        setLeablData(info, true)
                    } else {
                        for (tagBean in it) {
                            FlexBoxUtils.addChildToFlexboxLayout(it, true, binding.flboxSpecial, tagBean, 1)
                        }
                    }
                } else {
                    setLeablData(infoBean, true)
                }
            }
        })
        //基础设施标签
        viewModel.labelCongigLD4Base.observe(this, Observer {
            if (it.checkNotNull()) {
                totalTag4Fac.addAll(it)
                FlexBoxUtils.tagSelectList2.clear()
                binding.flboxBase.removeAllViews()
                if (isNewAdd) {//新增
                    if (SpUtils.getInstance().getAddEditOnlineWineyInfoJson().checkNotNull()) {
                        //草稿箱取出
                        val info = CommonUtil.jsonToBean(
                            SpUtils.getInstance().getAddEditOnlineWineyInfoJson(), WineryDataInfoBean::class.java
                        )
                        setLeablData(info, false)
                    } else {
                        for (tagBean in it) {
                            FlexBoxUtils.addChildToFlexboxLayout(it, true, binding.flboxBase, tagBean, 2)
                        }
                    }
                } else {
                    setLeablData(infoBean, false)
                }
            }
        })
        //创建&编辑酒窖
        viewModel.createEditWinery.observe(this, Observer {
            hideLoading()
            if (it) {
                //清空草稿
                SpUtils.getInstance().saveAddEditOnlineWineyInfo("")
                //通知删除临时图片
                EventBusUtils.sendNotify(MessageBus.msgid_img_upload_succ_need_delete_temp)
                //获取页面结束时间
                SensorsDataManager.instance.onDestroyTime()
                if (SensorsDataManager.instance.getBrowseTime() != 0L) {
                    SensorsDataManager.instance.operatorCreateCellar(SpUtils.getInstance().currentWineryInfo.wineryName, if (isNewAdd) "创建酒窖提审" else "编辑酒窖提审")
                }
                "提交成功，请等待审核".toast()
                if (it.checkNotNull() && it) {
                    finish()
                }
            } else {
                binding.imgCommit.isEnabled = true
            }
        })
        viewModel.wineryInfoDataLD.observe(this, Observer {
            if (it.checkNotNull()) {
                it[0].apply {
                    setTopInfo(dealerName.checkValue(), detailAddress.checkValue())
                }
            }
        })
    }

    var totalTag4Fac = mutableListOf<LabelConfigFacilityBean>()//基础
    var totalTag4Fea = mutableListOf<LabelConfigFacilityBean>()//特色
    var showSelectTag4Fac = mutableListOf<LabelConfigFacilityBean>()//基础
    var showSelectTag4Fea = mutableListOf<LabelConfigFacilityBean>()//特色

    //回显数据
    private fun echoInfoData(bean: WineryDataInfoBean) {
        setTopInfo(bean.wineryName.checkValue(), bean.detailAddress.checkValue())
        //封面
        selectCoverAfter(bean.wineryImg.checkValue())
        binding.etDesc.setText(bean.wineryDesc.checkValue())
        binding.etPrice.setText(bean.consumptionPrice.toString())
        //营业时间
        mStartTime = bean.startTime
        mEndTime = bean.endTime
        binding.tvTime.setText("${bean.startTime}-${bean.endTime}")
        binding.etPhone.setText(bean.wineryDealerPhone.checkValue())
        dealerCode = bean.dealerCode

        //轮播图
        mMediaPathList = if (bean.winerySlideshow.checkNotNull()) CommonUtil.jsonToList(bean.winerySlideshow.checkValue(), WineryCoverBean::class.java) else mutableListOf()
        mImageVideoAdapter.setData(mMediaPathList)
        mTouchHelper = RecyUtils.itemTouchHelper4EditWinery(mImageVideoAdapter, mMediaPathList, Constants.PUBLISH_IMG_MAX)
        viewModel.setItemHelper2EditWinery(binding.rvImagevideo, mTouchHelper, mImageVideoAdapter)
        mImageVideoAdapter.notifyDataSetChanged()
        //标签回显
        //选中的tag
        showSelectTag4Fac = bean.wineryLabelConfigFacility
        showSelectTag4Fea = bean.wineryLabelConfigFeature

    }

    private fun setTopInfo(wineryName: String,  detailAddress: String) {
        binding.tvWineryName.text = wineryName
        binding.tvWineryArea.text = detailAddress
    }

    private fun initListener() {
        binding.ivBack.setOnClickListener(this)
        binding.tvTime.setOnClickListener(this)
        binding.tvAddPic.setOnClickListener(this)
        binding.ivFragmentAgencyImage.setOnClickListener(this)
        binding.flNoImg.setOnClickListener(this)
        binding.ivDel.setOnClickListener(this)
        binding.imgPreview.setOnClickListener(this)
        binding.imgCommit.setOnClickListener(this)
    }

    private fun initView() {
        initImgVideoUpload()
        binding.etDesc.setFilters(arrayOf(InputFilter.LengthFilter(500)))
        EditInputUtils.numEditText(binding.etDesc, binding.tvWordNum, 500)
        if (isNewAdd) {
            //联系电话默认展示：该酒窖经营者-负责人手机号
            binding.etPhone.setText(SpUtils.getInstance().loadUserBean.data.phone.checkValue())
        }
    }

    var mMediaPathList = mutableListOf<WineryCoverBean>()
    private lateinit var mTouchHelper: ItemTouchHelper
    private lateinit var mImageVideoAdapter: EditWineryUploadImageVideoAdapter

    //初始化图片视频上传
    private fun initImgVideoUpload() {
        mImageVideoAdapter = EditWineryUploadImageVideoAdapter(this)
        binding.rvImagevideo.addItemDecoration(SpacesRightDec(dip2px(8)))
        binding.rvImagevideo.addItemDecoration(SpacesVerticalDec(dip2px(10)))
        binding.rvImagevideo.adapter = mImageVideoAdapter
        mTouchHelper = RecyUtils.itemTouchHelper4EditWinery(mImageVideoAdapter, mMediaPathList, Constants.PUBLISH_IMG_MAX)
        viewModel.setItemHelper2EditWinery(binding.rvImagevideo, mTouchHelper, mImageVideoAdapter)
        mImageVideoAdapter.setOnClickListener(this)
    }

    override fun onItemClick(pos: Int, list: List<WineryCoverBean>?) {
        //进入大图
        val urlList = mutableListOf<String>()
        for (datum in list as List<WineryCoverBean>) {
            urlList.add(if (datum.type == 0) datum.coverUrl else datum.videoUrl)
        }
        seeBigImg(urlList, pos, emptyList())
    }

    override fun onAddItemClick() {
        var isHaveVideo = false
        for (bean in mMediaPathList) {
            if (bean.type == 1) {
                isHaveVideo = true
            }
        }
        WineryAboutUtils.uploadImgVideo(this, !isHaveVideo, mMediaPathList.size, 9)
    }

    override fun onDeleteItemClick(pos: Int, list: List<WineryCoverBean>?) {
        PopUtils.showOkCancelDialog(this, "确认删除", object : PopUtils.ICallBack {
            override fun clickOk() {
                mTouchHelper = RecyUtils.itemTouchHelper4EditWinery(mImageVideoAdapter, mMediaPathList, Constants.PUBLISH_IMG_MAX)
                if (!isNewAdd) {//回显
                    mMediaPathList.removeAt(pos)
                    viewModel.setItemHelper2EditWinery(binding.rvImagevideo, mTouchHelper, mImageVideoAdapter)
                } else {//新增
                    mMediaPathList.removeAt(pos)
                    viewModel.setItemHelper2EditWinery(binding.rvImagevideo, mTouchHelper, mImageVideoAdapter)
                    mImageVideoAdapter.setData(mMediaPathList)
                }
                "删除成功".toast()
                mImageVideoAdapter.notifyDataSetChanged()
            }

            override fun clickCancel() {

            }

        }, false, "确认", "取消")
    }

    override fun onVideoCoversClick() {
    }

    //封面
    var coverUrlPath = ""
    var mStartTime = "09:00"
    var mEndTime = "22:00"
    var wineryFacility = ""
    var wineryFeature = ""

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back -> {
                tempSave()
            }
            R.id.iv_fragment_agency_image -> {
                seeBigImg(mutableListOf(coverUrlPath), 0, emptyList())
            }
            R.id.tv_time -> {
                //选择营业时间段
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    onClickSelectSchoolTime()
                }
            }
            R.id.fl_no_img, R.id.tv_add_pic -> {
                //添加封面图片
                selectSingleImg()
            }
            R.id.iv_del -> {
                //删除图片
                PopUtils.showOkCancelDialog(this, "确认删除", object : PopUtils.ICallBack {
                    override fun clickOk() {
                        binding.flNoImg.visibility = View.VISIBLE
                        binding.ivDel.visibility = View.GONE
                        coverUrlPath = ""
                        "删除成功".toast()
                    }

                    override fun clickCancel() {

                    }

                }, false, "确认", "取消")
            }
            R.id.img_preview -> {
                //预览
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    previewOption()
                }
            }
            R.id.img_commit -> {
                //提交审核
                if (checkLimit()) {
                    if (!DoubleClickHelper.isOnDoubleClick()) {
                        binding.imgCommit.isEnabled = false
                        showLoading()
                        uoloadFile()
                    }
                }
            }
        }
    }

    private lateinit var countDownTimer: CountDownTimer
    var uploadLoadingDialog: AlertDialog? = null
    fun showLoading() {
        uploadLoadingDialog = com.hankol.winecellar.utils.PopUtils.uploadLoadingDialog(this@EditOnlineWinecellarActivity, object : com.hankol.winecellar.utils.PopUtils.ICallback4Progress {
            override fun progressCallback(progress: MyCircleProgress, tvProgress: TextView) {
                countDownTimer = object : CountDownTimer(60000, 3000) {
                    override fun onTick(millisUntilFinished: Long) {
                        val pro = (60000 - millisUntilFinished) / 1000
                        progress.setMax(60)
                        progress.setCurrent(pro.toInt())
                    }

                    override fun onFinish() {}
                }.start()
            }
        })
        if (!uploadLoadingDialog!!.isShowing) {
            uploadLoadingDialog!!.show()
        }
    }

    fun hideLoading() {
        binding.imgCommit.isEnabled = true
        countDownTimer.cancel()
        if (uploadLoadingDialog.checkNotNull()) {
            uploadLoadingDialog!!.dismiss()
        }
    }

    private fun seeBigImg(coverUrlList: MutableList<String>, position: Int, descList: List<String>
    ) {
        //查看大图
        val bundle = Bundle()
        bundle.putStringArrayList(Constants.KEY_URLS, coverUrlList as ArrayList<String>)
        bundle.putInt(Constants.KEY_INDEX, position)
        bundle.putStringArrayList(Constants.KEY_COMMENT_CONTENT, if (descList.size == 0) ArrayList<String>() else descList as ArrayList<String>)
        bundle.putStringArrayList(Constants.KEY_COMMENT_TITLE, arrayListOf())
        ActivityRouter.startActivity(ActivityRouter.WINE_CELLAR.IMG_VIDEO_DETAIL, bundle)
    }

    private fun selectSingleImg() {
        if (!DoubleClickHelper.isOnDoubleClick()) {
            PermissionsUtils.getInstance().chekPermissions(this, PermissionCollection.CUSTOM.addPermissionList(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA), object : PermissionsCall() {
                override fun permissionsPass() {
                    ImagePicker.withMulti(WeChatPresenter().isShowVideo(false)).mimeTypes(MimeType.ofImage()).filterMimeTypes(MimeType.GIF).cropSaveInDCIM(false).showCamera(true).showCameraOnlyInAllMediaSet(true)
                        //设置剪裁比例
                        .setCropRatio(1, 1)
                        //设置剪裁框间距，单位px
                        .cropRectMinMargin(50)
                        //是否圆形剪裁，圆形剪裁时，setCropRatio无效
                        //设置剪裁模式，留白或充满  CropConfig.STYLE_GAP 或 CropConfig.STYLE_FILL
                        .cropStyle(CropConfig.STYLE_FILL)
                        //设置留白模式下生成的图片背景色，支持透明背景
                        .cropGapBackgroundColor(Color.TRANSPARENT).crop(this@EditOnlineWinecellarActivity) { items ->
                            try {
                                selectCoverAfter(items[0].cropUrl)
                            } catch (e: Exception) {
                                e.message
                            }
                        }
                }
            })
        }

//        ImagePicker.withCrop(RedBookPresenter())//设置presenter
//                .setMaxCount(1)//设置选择数量
//                .showCamera(true)//设置显示拍照
//                .setColumnCount(4)//设置列数
//                .mimeTypes(MimeType.ofImage())//设置需要加载的文件类型
//                .filterMimeTypes(MimeType.GIF)//设置需要过滤掉的文件类型
//                .assignGapState(false)//强制留白模式
//                .setFirstImageItem(null)//设置上一次选中的图片
//                .setFirstImageItemSize(1, 1)//设置上一次选中的图片地址
//                .setVideoSinglePick(true)//设置视频单选
//                .setMaxVideoDuration(1200000L)//设置可选区的最大视频时长
//                .setMinVideoDuration(3000L)//设置视频可选取的最小时长
//                .pick(this, object : OnImagePickCompleteListener {
//                    override fun onImagePickComplete(items: ArrayList<ImageItem>) {
//                        selectCoverAfter(items[0].path.checkValue())
//                    }
//                })
    }

    private fun selectCoverAfter(path: String) {
        if (path.checkNotNull()) {
            binding.flNoImg.visibility = View.GONE
            binding.ivDel.visibility = View.VISIBLE
            //图片剪裁回调，主线程
            //注意：剪裁回调里的ImageItem中getCropUrl()才是剪裁过后的图片地址
            coverUrlPath = path
            binding.ivFragmentAgencyImage.load(ContextUtils.getCurApplication().applicationContext, path)
        }
    }

    private fun uoloadFile() {
        //上传酒窖封面
        if (!coverUrlPath.startsWith("http")) {//封面是本地路径
            UploadMediaUtils.uploadImages(arrayListOf(coverUrlPath), object : UploadMediaUtils.UploadImageListener {
                override fun onComplete(questionRespT: MultiImageResp?) {
                    if (questionRespT.checkNotNull()) {
                        if (questionRespT!!.getData().size > 0) {
                            coverUrlPath = questionRespT.getData()[0].ok
                            uploadBannerImgVideo()
                        }
                    }
                }
            })
        } else {//封面为图片url
            uploadBannerImgVideo()
        }
    }

    private fun uploadBannerImgVideo() {
        val imgList4Path = mutableListOf<WineryCoverBean>()
        val imgList4Url = mutableListOf<String>()
        val indexList4Img = mutableListOf<Int>()

        val videoList4Path = mutableListOf<WineryCoverBean>()
        val videoList4Url = mutableListOf<String>()
        val indexList4Video = mutableListOf<Int>()
        mMediaPathList.forEachIndexed { index, wineryCoverBean ->
            if (wineryCoverBean.type == 0) {//图片
                if (wineryCoverBean.coverUrl.startsWith("http")) {//url
                    imgList4Url.add(wineryCoverBean.coverUrl.checkValue())
                } else {//path
                    imgList4Path.add(wineryCoverBean)
                    indexList4Img.add(index)
                }
            } else {//视频
                if (wineryCoverBean.videoUrl.startsWith("http")) {//url
                    videoList4Url.add(wineryCoverBean.videoUrl.checkValue())
                } else {//path
                    videoList4Path.add(wineryCoverBean)
                    indexList4Video.add(index)
                }
            }
        }
        if (imgList4Path.size > 0) {//需要上传的图片  无视频
            val needUploadImgPathList = mutableListOf<String>()
            for (coverBean in imgList4Path) {
                needUploadImgPathList.add(coverBean.coverUrl)
            }
            UploadMediaUtils.uploadImages(needUploadImgPathList as java.util.ArrayList<String>?, object : UploadMediaUtils.UploadImageListener {
                override fun onComplete(questionRespT: MultiImageResp?) {
                    val upsuccUrlList = mutableListOf<String>()
                    if (questionRespT.checkNotNull()) {
                        if (questionRespT!!.getData().size > 0) {
                            for (bean in questionRespT.getData()) {
                                upsuccUrlList.add(bean.ok)
                            }
                        }
                    }
                    indexList4Img.forEachIndexed { index, pathIndex ->
                        mMediaPathList[pathIndex].coverUrl = upsuccUrlList[index]
                    }
                    if (videoList4Path.size == 0) {
                        //都是图片
                        netCommit()
                    } else {
                        //有视频---上传视频
                        mMediaPathList.removeAll(videoList4Path)
                        uploadVideo(videoList4Path[0].videoUrl, indexList4Video)
                    }
                }
            })
        } else if (videoList4Path.size > 0) {
            //有视频---上传视频
            mMediaPathList.removeAll(videoList4Path)
            uploadVideo(videoList4Path[0].videoUrl, indexList4Video)
        } else {
            //没有新增(删减或者没有修改的情况)
            netCommit()
        }
    }

    private fun netCommit() {
        if (mMediaPathList.checkNotNull()) {
            viewModel.reqEditWinery(coverUrlPath, CommonUtil.beanToJson(mMediaPathList), binding.etPrice.text.toString(), mStartTime, mEndTime, binding.etPhone.text.toString(), binding.etDesc.text.toString(), CommonUtil.list2str(wineryFacilityList), CommonUtil.list2str(wineryFeatureList))
        } else {
            binding.imgCommit.isEnabled = true
            hideLoading()
        }
    }

    fun uploadVideo(videoPath: String, indexList4Video: List<Int>) {
        UploadMediaUtils.uploadVideo(videoPath, object : UploadMediaUtils.UploadVideoListener {
            override fun onProgress(uploadBytes: Long, totalBytes: Long) {
            }

            override fun onComplete(videoUrl: String?, videoCoverUrl: String?) {
                for (index in indexList4Video) {
                    mMediaPathList.add(index, WineryCoverBean(videoCoverUrl.checkValue(), videoUrl.checkValue(), 1))
                }
                netCommit()
            }
        })
    }

    //存标签id 的list
    val wineryFacilityList = mutableListOf<String>()//基础
    val wineryFeatureList = mutableListOf<String>()//特色

    //存标签名称的list 预览要用
    val wineryFacilityNameList = mutableListOf<String>()//基础
    val wineryFeatureNameList = mutableListOf<String>()//特色
    fun checkLimit(): Boolean {
        if (TextUtils.isEmpty(coverUrlPath)) {
            "酒窖封面图不能为空".toast()
            return false
        }
        if (mMediaPathList.size == 0) {
            "酒窖详情轮播图不能为空".toast()
            return false
        }
        if (mMediaPathList.size < 5) {
            "酒窖详情图至少上传5张".toast()
            return false
        }
        if (TextUtils.isEmpty(binding.etDesc.text.toString().trim())) {
            "酒窖介绍不能为空".toast()
            return false
        }
        if (TextUtils.isEmpty(binding.etPrice.text.toString())) {
            "人均价格不能为空".toast()
            return false
        }
//        if (TextUtils.isEmpty(mStartTime)) {
//            "营业时间不能为空".toast()
//            return false
//        }
        if (TextUtils.isEmpty(binding.etPhone.text.toString())) {
            "酒窖联系电话不能为空".toast()
            return false
        }
        if (binding.etPhone.text.toString().length != 11) {
            "联系电话必须11位".toast()
            return false
        }
        wineryFacilityList.clear()
        wineryFeatureList.clear()
        wineryFacilityNameList.clear()
        wineryFeatureNameList.clear()
        for (tagBean in FlexBoxUtils.tagSelectList1) {//特色
            wineryFeatureList.add("${tagBean.id}")
            wineryFeatureNameList.add("${tagBean.labelName.checkValue()}")
        }
        for (tagBean in FlexBoxUtils.tagSelectList2) {//基础
            wineryFacilityList.add("${tagBean.id}")
            wineryFacilityNameList.add("${tagBean.labelName.checkValue()}")
        }
        if (wineryFeatureList.size == 0) {
            "酒窖特色不能为空".toast()
            return false
        }
        if (wineryFacilityList.size == 0) {
            "基础设施不能为空".toast()
            return false
        }
        return true
    }

    //预览
    private fun previewOption() {
        if (checkLimit()) {
            wineryFacility = CommonUtil.join(wineryFacilityNameList.toTypedArray(), ",")
            wineryFeature = CommonUtil.join(wineryFeatureNameList.toTypedArray(), ",")
            val bean = WineryDetailPriewBean(
                coverUrlPath, mMediaPathList, binding.etDesc.text.toString(), binding.etPrice.text.toString().toInt(), mStartTime, mEndTime, binding.etPhone.text.toString(), wineryFacility, wineryFeature, if (infoBean.checkNotNull()) infoBean!!.distance else 0
            )
            val bundle = Bundle()
            bundle.putString("key_winery_detail_priew_bean", CommonUtil.beanToJson(bean))
            ActivityRouter.startActivity(ActivityRouter.WINE_CELLAR.WINCE_CELLAR_DETAIL, bundle)
        }
    }

    //选择营业时间
    fun onClickSelectSchoolTime() {
        com.hankol.winecellar.utils.PopUtils.showHourMinuteTimeSectionSelectDialog(this, object : PopUtils.IitemCallBackStr {
            override fun onOkClick(startTimeStr: String, endTimeStr: String) {
                binding.tvTime.text = "${startTimeStr}-${endTimeStr}"
                mStartTime = startTimeStr
                mEndTime = endTimeStr
            }
        })
    }

    //标签回显
    fun setLeablData(bean: WineryDataInfoBean?, isSpecial: Boolean) {
        bean?.let {
            if (isSpecial) {
                FlexBoxUtils.tagSelectList1.addAll(it.wineryLabelConfigFeature)
                //回显 特色
                for (facilityBean in totalTag4Fea) {
                    for (fac in showSelectTag4Fea) {
                        if (facilityBean.id == fac.id) {
                            facilityBean.checked = true
                        }
                    }
                }

                for (bean1 in totalTag4Fea) {
                    FlexBoxUtils.addChildToFlexboxLayout(totalTag4Fea, true, binding.flboxSpecial, bean1, 1)
                }
            } else {
                FlexBoxUtils.tagSelectList2.addAll(it.wineryLabelConfigFacility)
                //回显 基础设施
                for (feaBean in totalTag4Fac) {
                    for (fea in showSelectTag4Fac) {
                        if (feaBean.id == fea.id) {
                            feaBean.checked = true
                        }
                    }
                }
                for (bean2 in totalTag4Fac) {
                    FlexBoxUtils.addChildToFlexboxLayout(totalTag4Fac, true, binding.flboxBase, bean2, 2)
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_select_img_video_path_list) {
            if (messageBus.param1 is String) {//视频  mMediaPathList.add(0, WineryCoverBean("", newPath.checkValue(), 1))
                FileUtils.copyVideoFile(messageBus.param1.toString(), object : FileUtils.OnCopyFileListener {
                    override fun onCopyOver(filePath: String?) {
                        mMediaPathList.add(0, WineryCoverBean("", filePath.checkValue(), 1))
                    }

                    override fun onCopyError() {
                    }

                })
            } else if (messageBus.param1 is List<*>) {//图片
                var list = messageBus.param1 as List<String>
                for (imageItem in list) {
                    mMediaPathList.add(WineryCoverBean(imageItem, "", 0))
                }
            }
            //选择轮播
            mTouchHelper = RecyUtils.itemTouchHelper4EditWinery(mImageVideoAdapter, mMediaPathList, Constants.PUBLISH_IMG_MAX)
            viewModel.setItemHelper2EditWinery(binding.rvImagevideo, mTouchHelper, mImageVideoAdapter)
            mImageVideoAdapter.setData(mMediaPathList)
            mImageVideoAdapter.notifyDataSetChanged()
        }
    }

    //保存草稿
    fun tempSave() {
        PopUtils.showOkCancelDialog(this, "保存当前信息", object : PopUtils.ICallBack {
            override fun clickOk() {
                val infoBean = WineryDataInfoBean()
                infoBean.apply {
                    wineryImg = coverUrlPath
                    wineryDesc = binding.etDesc.text.toString()
                    consumptionPrice = if (binding.etPrice.text.toString().checkNotNull()) binding.etPrice.text.toString().toInt() else 0
                    startTime = mStartTime
                    endTime = mEndTime
                    wineryDealerPhone = binding.etPhone.text.toString()
                    winerySlideshow = if (mMediaPathList.size == 0) "" else CommonUtil.beanToJson(mMediaPathList)
                    wineryLabelConfigFacility = FlexBoxUtils.tagSelectList2 as ArrayList<LabelConfigFacilityBean>
                    wineryLabelConfigFeature = FlexBoxUtils.tagSelectList1 as ArrayList<LabelConfigFacilityBean>
                }
                SpUtils.getInstance().saveAddEditOnlineWineyInfo(CommonUtil.beanToJson(infoBean))
                SensorsDataManager.instance.operatorCellarOut(SpUtils.getInstance().currentWineryInfo.wineryName)
                finish()
            }

            override fun clickCancel() {
                SpUtils.getInstance().saveAddEditOnlineWineyInfo("")
                SensorsDataManager.instance.operatorCellarOut(SpUtils.getInstance().currentWineryInfo.wineryName)
                finish()
            }

        }, false, "确认", "取消")
    }

    //获取草稿箱
    fun getTempSave() {
        if (SpUtils.getInstance().getAddEditOnlineWineyInfoJson().checkNotNull()) {//草稿箱取出
            val it = CommonUtil.jsonToBean(
                SpUtils.getInstance().getAddEditOnlineWineyInfoJson(), WineryDataInfoBean::class.java
            )
            if (it.checkNotNull()) {
                infoBean = it
                //回显数据
                echoInfoData(it)
                reqLeabl()
            }
        } else {
            if (!isNewAdd) {//编辑 回显
                val wineryCode = SpUtils.getInstance().getCurrentWineryInfo().wineryCode
                val dealerCode = SpUtils.getInstance().getCurrentWineryInfo().dealerCode
                viewModel.reqgetWineryDataInfo(fromType, wineryCode, dealerCode)
            } else {
                //新增
                reqLeabl()
                //新增
                val dealerCode = SpUtils.getInstance().getCurrentWineryInfo().dealerCode
                viewModel.reqgetWineryList(SpUtils.getInstance().loadUserBean.data.phone.checkValue(), dealerCode)
            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()

    }

    override fun onBackPressed() {
//        super.onBackPressed()
        tempSave()
    }
}